import {getUsername, getRole} from "./utils.js"

function getReview(){
    $.ajax({
        url: "http://www.woniu-news.com:8082/getReviewList.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                let context = ""
                for(let item of resp.data){
                    context += `
                        <tr>
                            <td>${item.title}</td>
                            <td>${item.username}</td>
                            <td>${item.context}</td>
                            <td>${item.time}</td>
                            <td> <a href="javascript:void(0);" data-id="${item.id}" class="delete">删除</a></td>
                        </tr>
                        `
                }
                $(".tbody").html(context)
            } else if (resp.code === 202) {
                $(".tbody").html(`
                        <tr>
                            <td colspan="5">暂无数据</td>
                        </tr>
                    `)
            } else if (resp.code === 401) {
                alert(resp.message)
                window.location.href = "index.html"
            } else {
                alert(resp.message)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function deleteById(rid){
    const username = getUsername()
    const role = getRole()

    $.ajax({
        url: "http://www.woniu-news.com:8082/deleteReviewById.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        data: {
            username,
            role,
            rid
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                alert(resp.message)
                getReview()
            } else {
                alert(resp.message)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}


getReview()

$(document).on("click", ".delete", function () {
    const rid = $(this).attr("data-id")
    deleteById(rid)
})